import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../shared/smartadmin.config'
import { createNoSubstitutionTemplateLiteral } from 'typescript'

declare var $: any
declare var echarts: any
@Component({
  selector: 'sa-bom-hold',
  templateUrl: './bom-hold.component.html',
  styleUrls: ['./bom-hold.component.css']
})
export class BomHoldComponent implements OnInit {
  tableData: any = [] // table的表单数据
  BomCodeInfo: any = {} // BOM详情页的要遍历对象
  totalCounts: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  fileUp: string = ''
  fileToUpload: any = [] //上传文件回调参数
  activeSelected: string = '' //row高亮
  // 查询参数
  bomNumber: string = '' // BOM编码
  enterMan: string = '' // 录入人
  startTime: any = '' // 开始时间
  endTime: any = '' // 结束时间
  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {})
  }
  ngOnInit() {
    this.load()
    this.initAddBom()
  }
  totalCountTab: number = 0
  pageSizeTab: number = 10
  curPageTab: number = 1 //分页当前页
  //初始化加载list数据
  load() {
    let param = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        bomNumber: this.bomNumber,
        enterMan: this.enterMan,
        startTime: this.startTime,
        endTime: this.endTime
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(param)
    this.jsonApiService.http('bomMaterialController/findBomList.html', reqdata).subscribe(result => {
      let data = []
      if (result.isSuccess && result.exhibitDatas) {
        data = result.exhibitDatas
        for (let i = 0; i < data.length; i++) {
          let string = ''
          for (let j = 0; j < data[i].materielList.length; j++) {
            if (data[i].materielList[j].materielType) {
              let str =
                '[ ' +
                data[i].materielList[j].materielTypeStr +
                ':' +
                data[i].materielList[j].productName +
                ', ' +
                data[i].materielList[j].num +
                '个 ]'
              string += str + ' ; '
            }
          }
          data[i].str = string
          if (string.length > 80) {
            let s = string.substring(0, 80)
            data[i].sortstr = s + '...'
          } else {
            data[i].sortstr = string
          }
        }
        this.tableData = result.exhibitDatas
        this.totalCounts = result.recordCount
      }
    })
  }

  //时间选中回调
  datePickerSelected(time) {
    this.startTime = time.startTime
    this.endTime = time.endTime
  }
  delKey(type) {
    if (type == 'enterMan') {
      this.enterMan = ''
    }
    if (type == 'bomNumber') {
      this.bomNumber = ''
    }
  }
  // 查询
  tableSearch() {
    this.curPage = 1
    this.load()
  }
  // 显示导入的弹框
  showImportModal(modal) {
    modal.show()
  }
  // 关闭导入的弹框
  cancelUp(val) {
    val.hide()
    this.fileToUpload = []
  }
  //下载模板
  load_module() {
    var elemIF = document.createElement('iframe')
    elemIF.src = config.BaseURL + 'resources/template/bom-Template.xlsx'
    elemIF.style.display = 'none'
    document.body.appendChild(elemIF)
  }
  // 清空input type=file输入框的值
  clearFile() {
    this.fileUp = ''
  }

  //文件上传change回调
  fileChange(files) {
    console.log(files)
    // 这一层循环判断格式是否正确
    for (let index = 0; index < files.length; index++) {
      console.log(files.item(index))
      const isEXCEL =
        files.item(index).type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        files.item(index).type === 'application/vnd.ms-excel'
      if (!isEXCEL) {
        this.jsonApiService.message('上传文件只能是 excel格式!')
        return
      } else {
        let isSame = false
        //
        for (let i = 0; i < this.fileToUpload.length; i++) {
          if (this.fileToUpload[i].name == files.item(index).name) {
            this.jsonApiService.message('上传文件重复!')
            isSame = true
            break
          }
        }
        if (!isSame) {
          this.fileToUpload.push(files.item(index))
        }
      }
    }
  }

  //导入submit
  submitData(val) {
    if (this.fileToUpload.length == 0) {
      this.jsonApiService.message('请上传文件')
      return false
    }
    for (let i = 0; i < this.fileToUpload.length; i++) {
      let postParam = new FormData()
      postParam.append('file', this.fileToUpload[i])
      this.jsonApiService.form_http('bomMaterialController/uploadBomExcelByErp.html', postParam).subscribe(data => {
        // this.jsonApiService.message("第["+i+"]份"+data.message);
        this.jsonApiService.message(data.message)
        // if (data.success) {
        //   val.hide()
        //   this.fileToUpload = []
        //   this.load()
        // } else {
        //   val.hide()
        //   this.fileToUpload = []
        // }
        if (i === this.fileToUpload.length - 1) {
          val.hide()
          this.fileToUpload = []
          this.load()
        }
      })
    }
  }

  //查看详情
  detail_domCode(row, id, modal) {
    modal.show()
    // $("#BomCodeDetail").modal("show")
    this.activeSelected = id
    this.BomCodeInfo = row
  }
  // 删除dom编码
  del_domCode(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除').then(() => {
      let reqdata = 'id=' + row.id
      this.jsonApiService.http('bomMaterialController/delBom.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
        }
      })
    })
  }
  // 分页回调
  paginate(e) {
    this.activeSelected = ''
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  // 刷新表
  refresh() {
    this.load()
  }

  page: any = {
    bomCode: '',
    desc: ''
  }
  bomTitle: any = '' // 添加和编辑BOM编码的标题
  bomBtn: any = '提交' // 添加和编辑的按钮文字
  editId: any = '' // 编辑的BOM编码Id
  // 三个数组  最后根据标志判断在放入
  masterList: any = { selected: true, arr: [{}] } // 主机数据
  sensorList: any = { selected: true, arr: [{}] } // 传感器数数据
  wireList: any = { selected: true, arr: [{}] } // 线材数据

  // 下面三个数组防止name选择框修改时修改masterList导致页面选择框重新渲染
  masterArr: any = [] // 渲染页面的数组
  sensorArr: any = [] // 渲染页面的数组
  wireArr: any = [] // 渲染页面的数组

  //三个材料的名称 版本数据
  nameList: any = { host: [], sensor: [], wire: [] }

  // 添加Bom编码按钮弹框   请求材料的名称数据
  addBomCode(modal) {
    modal.show()
    // $("#addBomCodeModal").modal("show")
    this.bomTitle = '添加BOM编码'
    this.bomBtn = '提交'
    // this.jsonApiService.http("bomMaterialController/addBomInit.html",{}).subscribe(data => {
    // 	if(data.success){
    // 		// 版本的列表
    // 		this.nameList=data.data

    // 		// 初始化数据
    // 		this.page={
    // 			bomCode:'',
    // 			desc:"",
    // 		}
    // 		this.masterList={selected:true,arr:[]};// 主机数组
    // 		this.sensorList={selected:true,arr:[]}; // 传感器数组
    // 		this.wireList={selected:true,arr:[]}; // 线材数组
    // 		this.masterArr=[]
    // 		this.sensorArr=[]
    // 		this.wireArr=[]
    // 		// 初始化渲染长度  至少有一个
    // 		this.masterArr[0]=data.data.host[0]
    // 		this.sensorArr[0]=data.data.sensor[0]
    // 		this.wireArr[0]=data.data.wire[0]
    // 	}
    // })
  }
  //初始化请求
  initAddBom() {
    this.jsonApiService.http('bomMaterialController/addBomInit.html', {}).subscribe(data => {
      if (data.success) {
        // 版本的列表
        this.nameList = data.data

        // 初始化数据
        this.page = {
          bomCode: '',
          desc: ''
        }
        this.masterList = { selected: true, arr: [] } // 主机数组
        this.sensorList = { selected: true, arr: [] } // 传感器数组
        this.wireList = { selected: true, arr: [] } // 线材数组
        this.masterArr = []
        this.sensorArr = []
        this.wireArr = []
        // 初始化渲染长度  至少有一个
        this.masterArr[0] = data.data.host[0]
        this.sensorArr[0] = data.data.sensor[0]
        this.wireArr[0] = data.data.wire[0]
      }
    })
  }
  // 编辑BOM编码的弹框
  editBomCode(row, modal) {
    this.bomTitle = '编辑BOM编码'
    this.bomBtn = '保存'
    this.editId = row.id
    this.jsonApiService.http('bomMaterialController/addBomInit.html', {}).subscribe(data => {
      if (data.success) {
        // 版本的列表
        this.nameList = data.data
        this.page = {
          bomCode: row.bomNumber,
          desc: row.describe
        }
        // 先初始化再填充编辑的数据
        this.masterList = { selected: false, arr: [] } // 主机数组
        this.sensorList = { selected: false, arr: [] } // 传感器数组
        this.wireList = { selected: false, arr: [] } // 线材数组
        this.masterArr = []
        this.sensorArr = []
        this.wireArr = []

        for (let index = 0; index < row.materielList.length; index++) {
          const element = row.materielList[index]
          // 主机
          if (element.materielType == 1) {
            this.masterList.selected = true
            this.masterList.arr.push(element)
            // 占长度
            this.masterArr.push(element)
          } else if (element.materielType == 2) {
            // 传感器
            this.sensorList.selected = true
            this.sensorList.arr.push(element)
            // 占长度
            this.sensorArr.push(element)
          } else if (element.materielType == 3) {
            this.wireList.selected = true
            this.wireList.arr.push(element)
            // 占长度
            this.wireArr.push(element)
          }
        }
        // 如果三个没有勾选 但是要有一个初始的渲染长度
        if (!this.masterList.selected) {
          this.masterArr.push({})
        }
        if (!this.sensorList.selected) {
          this.sensorArr.push({})
        }
        if (!this.wireList.selected) {
          this.wireArr.push({})
        }
        // 初始化主机的选择框
        for (let j = 0; j < this.masterArr.length; j++) {
          const masterMaterielNumber = this.masterArr[j].materielNumber
          for (let index = 0; index < this.nameList.host.length; index++) {
            const hostMaterielNumber = this.nameList.host[index].materielNumber
            if (masterMaterielNumber && hostMaterielNumber == masterMaterielNumber) {
              this.masterArr[j]['index'] = index
            }
          }
        }
        for (let j = 0; j < this.sensorArr.length; j++) {
          const sMaterielNumber = this.sensorArr[j].materielNumber
          for (let index = 0; index < this.nameList.sensor.length; index++) {
            const sensorMaterielNumber = this.nameList.sensor[index].materielNumber
            if (sMaterielNumber && sensorMaterielNumber == sMaterielNumber) {
              this.sensorArr[j]['index'] = index
            }
          }
        }
        for (let j = 0; j < this.wireArr.length; j++) {
          const wMaterielNumber = this.wireArr[j].materielNumber
          for (let index = 0; index < this.nameList.wire.length; index++) {
            const wireMaterielNumber = this.nameList.wire[index].materielNumber
            if (wMaterielNumber && wireMaterielNumber == wMaterielNumber) {
              this.wireArr[j]['index'] = index
            }
          }
        }
        modal.show()
        // $("#addBomCodeModal").modal("show");
      }
    })
  }
  // 点击加号触发的回调
  addMaterial(type) {
    if (type == 1) {
      this.masterArr.push({})
    } else if (type == 2) {
      this.sensorArr.push({})
    } else if (type == 3) {
      this.wireArr.push({})
    }
  }
  // 点击删除的触发的回调
  deleteMaterial(type, index) {
    if (type == 1) {
      this.masterArr.splice(index, 1)
      this.masterList.arr.splice(index, 1)
    } else if (type == 2) {
      this.sensorArr.splice(index, 1)
      this.sensorList.arr.splice(index, 1)
    } else if (type == 3) {
      this.wireArr.splice(index, 1)
      this.wireList.arr.splice(index, 1)
    }
  }
  // 材料名改变
  nameChange(value, type, index) {
    if (type == 'master') {
      // 如果有num
      if (value) {
        if (this.masterList.arr[index] && this.masterList.arr[index].num) {
          let num = this.masterList.arr[index].num
          // 对象中没有num
          this.masterList.arr[index] = JSON.parse(JSON.stringify(this.nameList.host[value]))
          this.masterList.arr[index].num = num
        } else {
          this.masterList.arr[index] = JSON.parse(JSON.stringify(this.nameList.host[value]))
        }
      } else {
        this.masterList.arr = []
      }
    } else if (type == 'sensor') {
      if (value) {
        if (this.sensorList.arr[index] && this.sensorList.arr[index].num) {
          let num = this.sensorList.arr[index].num
          this.sensorList.arr[index] = JSON.parse(JSON.stringify(this.nameList.sensor[value]))
          this.sensorList.arr[index].num = num
        } else {
          this.sensorList.arr[index] = JSON.parse(JSON.stringify(this.nameList.sensor[value]))
        }
      } else {
        this.sensorList.arr = []
      }
    } else if (type == 'wire') {
      if (value) {
        if (this.wireList.arr[index] && this.wireList.arr[index].num) {
          let num = this.wireList.arr[index].num
          this.wireList.arr[index] = JSON.parse(JSON.stringify(this.nameList.wire[value]))
          this.wireList.arr[index].num = num
        } else {
          this.wireList.arr[index] = JSON.parse(JSON.stringify(this.nameList.wire[value]))
        }
      } else {
        this.wireList.arr = []
      }
    }
  }
  // 数量减
  reduceNum(target, type, index) {
    let numInput = target.parentNode.parentNode.children[1]
    let val = Number(target.parentNode.parentNode.children[1].value)
    let numVal
    if (val < 1 || !val) {
      numVal = 1
    } else {
      if (val - 1 == 0) {
        numVal = 1
      } else {
        numVal = val - 1
      }
    }
    numInput.value = numVal //输入框
    if (type == 'master') {
      // 如果没有就给他一个对象
      if (!this.masterList.arr[index]) {
        this.masterList.arr.push({})
      }
      this.masterList.arr[index].num = numVal
    } else if (type == 'sensor') {
      if (!this.sensorList.arr[index]) {
        this.sensorList.arr.push({})
      }
      this.sensorList.arr[index].num = numVal
    } else if (type == 'wire') {
      if (!this.wireList.arr[index]) {
        this.wireList.arr.push({})
      }
      this.wireList.arr[index].num = numVal
    }
  }
  // 数量加
  addNum(target, type, index) {
    let numInput = target.parentNode.parentNode.children[1]
    let val = Number(target.parentNode.parentNode.children[1].value)
    let numVal
    if (val < 1 || !val) {
      numVal = 1
    } else {
      numVal = val + 1
    }
    numInput.value = numVal //输入框
    if (type == 'master') {
      // 如果没有就给他一个对象
      if (!this.masterList.arr[index]) {
        this.masterList.arr.push({})
      }
      this.masterList.arr[index].num = numVal
    } else if (type == 'sensor') {
      if (!this.sensorList.arr[index]) {
        this.sensorList.arr.push({})
      }
      this.sensorList.arr[index].num = numVal
    } else if (type == 'wire') {
      if (!this.wireList.arr[index]) {
        this.wireList.arr.push({})
      }
      this.wireList.arr[index].num = numVal
    }
  }
  // 数量改变
  numChange(value, type, index) {
    // 对value的值进行判断
    if (type == 'master') {
      // 如果没有就给他一个对象
      if (!this.masterList.arr[index]) {
        this.masterList.arr.push({})
      }
      this.masterList.arr[index].num = value
    } else if (type == 'sensor') {
      if (!this.sensorList.arr[index]) {
        this.sensorList.arr.push({})
      }
      this.sensorList.arr[index].num = value
    } else if (type == 'wire') {
      if (!this.wireList.arr[index]) {
        this.wireList.arr.push({})
      }
      this.wireList.arr[index].num = value
    }
  }
  // 点击前面的选择框
  checkboxClick(type) {
    if (type == 'master') {
      this.masterList.selected = !this.masterList.selected
    } else if (type == 'sensor') {
      this.sensorList.selected = !this.sensorList.selected
    } else if (type == 'wire') {
      this.wireList.selected = !this.wireList.selected
    }
  }
  // 关闭添加的弹窗
  closeAddBomModal(modal) {
    modal.hide()
    // $("#addBomCodeModal").modal("hide")
    // this.masterList={selected:false,arr:[]};// 主机数组
    // this.sensorList={selected:false,arr:[]}; // 传感器数组
    // this.wireList={selected:false,arr:[]}; // 线材数组
    // this.masterArr=[]
    // this.sensorArr=[]
    // this.wireArr=[]

    // 初始化数据
    this.page = {
      bomCode: '',
      desc: ''
    }
    this.masterList = { selected: true, arr: [] } // 主机数组
    this.sensorList = { selected: true, arr: [] } // 传感器数组
    this.wireList = { selected: true, arr: [] } // 线材数组
    this.masterArr = []
    this.sensorArr = []
    this.wireArr = []
    // 初始化渲染长度  至少有一个
    this.masterArr[0] = {}
    this.sensorArr[0] = {}
    this.wireArr[0] = {}
  }
  closeDetailModal(modal) {
    modal.hide()
    // $("#BomCodeDetail").modal("hide");
  }
  // 提交添加的数据
  submitModal(modal) {
    let array = [] // 给后台的数据
    let isOk = { flag: true, msg: '' } // 验证
    if (this.page.bomCode == '') {
      this.jsonApiService.message('请填写BOM编码')
      return
    }
    if (this.page.desc == '') {
      this.jsonApiService.message('请填写编码描述')
      return
    }
    if (this.masterList.selected) {
      if (this.masterList.arr.length == 0) {
        this.jsonApiService.message('请选择主机类型')
        return
      }
      for (let i = 0; i < this.masterList.arr.length; i++) {
        if (
          !this.masterList.arr[i].num ||
          this.masterList.arr[i].num == '' ||
          this.masterList.arr[i].num <= 0 ||
          !Number(this.masterList.arr[i].num)
        ) {
          isOk.flag = false
          isOk.msg = '请填写正确的主机数量'
        }
        if ((this.masterList.arr[i].num + '').split('.').length > 1) {
          isOk.flag = false
          isOk.msg = '主机数量请不要为小数'
        }
        array.push(this.masterList.arr[i])
      }
      let arr1 = [] //判断重复的数组
      for (let i = 0; i < this.masterList.arr.length; i++) {
        if (!this.masterList.arr[i].materielType) {
          isOk.flag = false
          isOk.msg = '请选择主机类型'
          break
        }
        if (arr1.indexOf(this.masterList.arr[i].materielNumber) == -1) {
          if (this.masterList.arr[i].materielNumber) {
            arr1.push(this.masterList.arr[i].materielNumber)
          }
        } else {
          isOk.flag = false
          isOk.msg = '主机类型重复'
        }
      }
    }
    if (this.sensorList.selected) {
      if (this.sensorList.arr.length == 0) {
        this.jsonApiService.message('请选择传感器类型')
        return
      }
      for (let i = 0; i < this.sensorList.arr.length; i++) {
        if (
          !this.sensorList.arr[i].num ||
          this.sensorList.arr[i].num == '' ||
          this.sensorList.arr[i].num <= 0 ||
          !Number(this.sensorList.arr[i].num)
        ) {
          isOk.flag = false
          isOk.msg = '请填写正确的传感器数量'
        }
        if ((this.sensorList.arr[i].num + '').split('.').length > 1) {
          isOk.flag = false
          isOk.msg = '传感器数量请不要为小数'
        }
        array.push(this.sensorList.arr[i])
      }
      let arr2 = [] //判断重复的数组
      for (let i = 0; i < this.sensorList.arr.length; i++) {
        if (!this.sensorList.arr[i].materielType) {
          isOk.flag = false
          isOk.msg = '请选择传感器类型'
          break
        }
        if (arr2.indexOf(this.sensorList.arr[i].materielNumber) == -1) {
          // 不为null
          if (this.sensorList.arr[i].materielNumber) {
            arr2.push(this.sensorList.arr[i].materielNumber)
          }
        } else {
          isOk.flag = false
          isOk.msg = '传感器类型重复'
        }
      }
    }
    if (this.wireList.selected) {
      if (this.wireList.arr.length == 0) {
        this.jsonApiService.message('请选择线材类型')
        return
      }
      for (let i = 0; i < this.wireList.arr.length; i++) {
        if (
          !this.wireList.arr[i].num ||
          this.wireList.arr[i].num == '' ||
          this.wireList.arr[i].num <= 0 ||
          !Number(this.wireList.arr[i].num)
        ) {
          isOk.flag = false
          isOk.msg = '请填写正确的线材数量'
        }
        if ((this.wireList.arr[i].num + '').split('.').length > 1) {
          isOk.flag = false
          isOk.msg = '线材数量请不要为小数'
        }
        array.push(this.wireList.arr[i])
      }
      let arr3 = [] // 判断是否重复的数组
      for (let i = 0; i < this.wireList.arr.length; i++) {
        if (!this.wireList.arr[i].materielType) {
          isOk.flag = false
          isOk.msg = '请选择线材类型'
          break
        }
        if (arr3.indexOf(this.wireList.arr[i].materielNumber) == -1) {
          if (this.wireList.arr[i].materielNumber) {
            arr3.push(this.wireList.arr[i].materielNumber)
          }
        } else {
          isOk.flag = false
          isOk.msg = '线材类型重复'
        }
      }
    }
    if (array.length == 0) {
      this.jsonApiService.message('请选择物料')
      return
    }
    if (!isOk.flag) {
      this.jsonApiService.message(isOk.msg)
      return
    }

    let obj = {}
    if (this.bomBtn == '保存') {
      obj = {
        id: this.editId,
        bomNumber: this.page.bomCode,
        describe: this.page.desc,
        materielList: JSON.stringify(array)
      }
    } else {
      obj = {
        bomNumber: this.page.bomCode,
        describe: this.page.desc,
        materielList: JSON.stringify(array)
      }
    }
    this.jsonApiService.http_obj('bomMaterialController/addBom.html', obj).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.closeAddBomModal(modal)
        // $("#addBomCodeModal").modal("hide")
        this.load()
      }
    })
  }
}
